<template>
  <div class="mobile-hot-showing" ref="containerRef">
    <!-- 顶部搜索栏 -->
    <div class="mobile-search-bar">
      <div class="page-title">
        <el-icon @click="goBack">
          <ArrowLeft />
        </el-icon>
        <span>热映影片</span>
      </div>
      <div class="search-input">
        <el-input
          v-model="search"
          placeholder="搜索电影"
          size="small"
          :prefix-icon="Search"
          clearable
          @keyup.enter="searchFilm"
        />
      </div>
    </div>

    <!-- 分类标签 -->
    <div class="mobile-category">
      <div class="category-tags">
        <el-tag
          v-for="(tag, index) in movieTags"
          :key="index"
          :class="{ 'active-tag': activeTag === index }"
          @click="filterByTag(index)"
          size="small"
        >
          {{ tag }}
        </el-tag>
      </div>
    </div>

    <!-- 电影列表 -->
    <div class="mobile-movie-list">
      <div class="movie-grid">
        <div
          v-for="item in movieList"
          :key="item.id"
          class="movie-item"
          @click="goToDetail(item.id)"
        >
          <div class="movie-poster">
            <img :src="item.photo" alt="电影海报" class="poster-image" />
            <div class="movie-score">{{ item.rating }}分</div>
          </div>
          <div class="movie-info">
            <div class="movie-name">{{ item.name }}</div>
            <div class="movie-director">导演: {{ item.director }}</div>
            <div class="movie-actors">主演: {{ item.actor }}</div>
            <div class="movie-type">类型: {{ item.type }}</div>
            <el-button type="danger" size="small" class="buy-button">
              购票
            </el-button>
          </div>
        </div>
      </div>

      <!-- 无数据提示 -->
      <el-empty v-if="movieList.length === 0" description="暂无电影数据" />
      
      <!-- 加载更多 -->
      <div class="loading-more" v-if="loading">
        <el-skeleton :rows="1" animated />
      </div>
      <div class="no-more" v-if="noMore">
        <span>没有更多数据了</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { Search, ArrowLeft } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { mobileReqAllFilm, mobileReqFilmByType } from '@/api/mobile'
import qs from 'qs'

// 路由
const router = useRouter()
const goBack = () => {
  router.back()
}

// 搜索
const search = ref('')
const searchFilm = () => {
  if (!search.value.trim()) {
    ElMessage.warning('请输入电影名称')
    return
  }
  resetList()
  loadMovies()
}

// 分类标签
const movieTags = ['全部', '动作', '喜剧', '爱情', '科幻', '恐怖', '动画']
const activeTag = ref(0)
const filterByTag = (index: number) => {
  activeTag.value = index
  resetList()
  loadMovies()
}

// 电影数据
const movieList = ref<any[]>([])
const currentPage = ref(1)
const pageSize = ref(6)
const total = ref(0)
const loading = ref(false)
const noMore = ref(false)

// 加载电影
const loadMovies = async () => {
  try {
    loading.value = true

    const params: any = {
      pageSize: pageSize.value,
      page: currentPage.value,
    }
    if (search.value.trim()) {
      params.name = search.value.trim()
    }
    if (activeTag.value !== 0) {
      params.type = movieTags[activeTag.value]
    }

    const result = activeTag.value === 0
      ? await mobileReqAllFilm(qs.stringify(params))
      : await mobileReqFilmByType(qs.stringify(params))

    if (result.code === 1) {
      if (currentPage.value === 1) {
        movieList.value = result.data.records
      } else {
        movieList.value = [...movieList.value, ...result.data.records]
      }
      total.value = result.data.total
      noMore.value = movieList.value.length >= total.value
    }
  } catch (error) {
    console.error('加载电影失败', error)
    ElMessage.error('加载电影失败')
  } finally {
    loading.value = false
  }
}

// 重置列表
const resetList = () => {
  movieList.value = []
  currentPage.value = 1
  noMore.value = false
}

// 加载更多
const loadMore = () => {
  if (loading.value || noMore.value) return
  currentPage.value++
  loadMovies()
}

// 跳转详情
const goToDetail = (id: number) => {
  router.push(`/mobile/detail/${id}`)
}

// 滚动监听
const containerRef = ref<HTMLElement | null>(null)

const handleScroll = () => {
  if (!containerRef.value) return

  const scrollTop = containerRef.value.scrollTop
  const clientHeight = containerRef.value.clientHeight
  const scrollHeight = containerRef.value.scrollHeight

  console.log('正在滚动')  // 🔥 测试：滚动时会打印！

  if (scrollHeight - scrollTop - clientHeight < 100 && !loading.value && !noMore.value) {
    console.log('到底了，加载更多')
    loadMore()
  }
}

// 防抖
function debounce(fn: Function, delay: number) {
  let timer: ReturnType<typeof setTimeout> | null = null
  return function (...args: any[]) {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn(...args)
    }, delay)
  }
}
const debounceHandleScroll = debounce(handleScroll, 200)

onMounted(() => {
  loadMovies()
  containerRef.value?.addEventListener('scroll', debounceHandleScroll)
})

onUnmounted(() => {
  containerRef.value?.removeEventListener('scroll', debounceHandleScroll)
})
</script>



<style scoped lang="scss">
.mobile-hot-showing {
  padding: 0 0 60px;
  height: 100vh;
  overflow-y: auto;
}

.mobile-search-bar {
  display: flex;
  flex-direction: column;
  padding: 10px 15px;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  position: sticky;
  top: 0;
  z-index: 10;

  .page-title {
    display: flex;
    align-items: center;
    margin-bottom: 10px;

    .el-icon {
      font-size: 20px;
      margin-right: 10px;
      cursor: pointer;
    }

    span {
      font-size: 18px;
      font-weight: bold;
    }
  }

  .search-input {
    width: 100%;
  }
}

.mobile-category {
  padding: 15px;

  .category-tags {
    display: flex;
    flex-wrap: nowrap;
    overflow-x: auto;
    padding-bottom: 5px;

    &::-webkit-scrollbar {
      display: none;
    }

    .el-tag {
      margin-right: 8px;
      cursor: pointer;
      flex-shrink: 0;

      &.active-tag {
        background-color: #ff6b6b;
        color: #fff;
        border-color: #ff6b6b;
      }
    }
  }
}

.mobile-movie-list {
  padding: 0 15px;

  .movie-grid {
    display: flex;
    flex-direction: column;
    gap: 15px;
  }

  .movie-item {
    display: flex;
    background-color: #fff;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  }

  .movie-poster {
    position: relative;
    width: 120px;
    height: 180px;
    flex-shrink: 0;

    .poster-image {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .movie-score {
      position: absolute;
      top: 5px;
      right: 5px;
      background-color: rgba(255, 107, 107, 0.9);
      color: #fff;
      padding: 2px 6px;
      border-radius: 10px;
      font-size: 12px;
      font-weight: bold;
    }
  }

  .movie-info {
    flex: 1;
    padding: 10px;
    display: flex;
    flex-direction: column;

    .movie-name {
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 8px;
    }

    .movie-director,
    .movie-actors,
    .movie-type {
      font-size: 13px;
      color: #606266;
      margin-bottom: 5px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .buy-button {
      margin-top: auto;
      align-self: flex-start;
      background-color: #ff6b6b;
      border-color: #ff6b6b;

      &:hover,
      &:focus {
        background-color: #ff8585;
        border-color: #ff8585;
      }
    }
  }
}

.loading-more {
  margin-top: 20px;
  padding: 10px 0;
  text-align: center;
}

.no-more {
  margin-top: 15px;
  padding: 10px 0;
  text-align: center;
  color: #909399;
  font-size: 14px;
}
</style>
